package com.tjsoft.demo.webChat.util;

import java.io.Writer;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
/**
 * 
 * xml解析
 * @author Administrator
 *
 */
public class XStreamFactory {
	protected static String PREFIX_CDATA = "<![CDATA[";
	protected static String SUFFIX_CDATA = "]]>";

	/**
	 * 初始化XStream 可支持某一字段可以加入CDATA标签 如果需要某一字段使用原文
	 * 就需要在String类型的text的头加上"<![CDATA["和结尾处加上"]]>"标签， 以供XStream输出时进行识别
	 * 比如一些特殊的字符<>无法被解析，可以通过此方法实现解析
	 * @param isAddCDATA
	 *        是否支持CDATA标签
	 * @return
	 */
	public static XStream init(boolean isAddCDATA) {
		XStream xstream = null;
	    //
		if (isAddCDATA) {
			xstream = new XStream(
					new XppDriver() {
						public HierarchicalStreamWriter createWriter(Writer out) {//创建一个输出驱动
							return new PrettyPrintWriter(out) {
								protected void writeText(QuickWriter writer, String text) {
									if (!text.startsWith(PREFIX_CDATA)) {
										text = PREFIX_CDATA + text + SUFFIX_CDATA;
									}
									writer.write(text);
								}
							};
						};
					 } 
					);
			
		} else {
			xstream = new XStream();
		}
		return xstream;
	}
}
